package factory;

import aspect.LogAspect;
import client.Client;
import client.ClientConfig;
import log.LogService;
import log.LogServiceImpl;
import server.Server;
import server.ServerConfig;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 工厂类
 */
public class MyFactory {

    public ClientConfig createClientConfig() {
        return new ClientConfig();
    }

    public ServerConfig createServerConfig() {
        return new ServerConfig();
    }

    public Thread createThread(Runnable runnable) {
        return new Thread(runnable);
    }

    public ExecutorService createThreadPool(int corePoolSize, int maximumPoolSize, int keepAliveTime) {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
    }

    public static LogService createLogService() {
        LogService logService = new LogServiceImpl();
        LogAspect logAspect = new LogAspect();

        LogService proxyService = (LogService) Proxy.newProxyInstance(MyFactory.class.getClassLoader(),
                logService.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    Object object = method.invoke(logService, args);
                    logAspect.after((String) args[0]);
                    return object;
                });

        return proxyService;
    }
}
